package com.shuyuwl.core.service.impl;

import com.google.common.collect.Lists;
import com.shuyuwl.core.domain.AbstractBaseDomain;
import com.shuyuwl.core.enums.ResultEnum;
import com.shuyuwl.core.enums.StatusEnum;
import com.shuyuwl.core.exception.SymServiceException;
import com.shuyuwl.core.repository.DaoRepository;
import com.shuyuwl.core.service.IDaoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * 该类是 业务逻辑类的抽象父类，该类中已包含各实体所需的基本方法
 * @Author ZChao
 * @Date 2019/9/4
 **/
@Slf4j
public class DaoServiceImpl<T extends AbstractBaseDomain, ID extends Serializable, R extends DaoRepository<T, ID>> implements IDaoService<T, ID, R> {

    @Autowired
    protected R repository;

    @Override
    public void add(Iterable<T> iterable) throws SymServiceException {
        try {
            iterable.forEach(domain -> this.save(domain));
        } catch (Exception e) {
            log.error("批量保存数据错误：{}", e);
            throw new SymServiceException(ResultEnum.BATCH_SAVE_DATA_ERROR);
        }
    }

    @Override
    public void delete(ID id) throws SymServiceException {
        try {
            repository.deleteById(id);
        } catch (Exception e){
            log.error("删除数据ID【{}】数据错误：{}", id, e);
            throw new SymServiceException(ResultEnum.REMOVE_BYID_ERROR);
        }
    }

    @Override
    public void delete(T domain) throws SymServiceException {
        try {
            repository.delete(domain);
        }catch (Exception e){
            log.error("删除数据【{}】数据错误：{}", domain, e);
            throw new SymServiceException(ResultEnum.REMOVE_ERROR);
        }
    }

    @Override
    public T save(T domain) throws SymServiceException {
        try {
            domain = repository.save(domain);
        } catch (Exception e) {
            log.error("保存数据错误：{}", e);
            throw new SymServiceException(ResultEnum.SAVE_DATA_ERROR);
        }
        return domain;
    }

    @Override
    @Transactional(readOnly = true,rollbackFor = Exception.class)
    public T get(ID id) throws SymServiceException {
        T result;
        try {
            result = repository.findById(id).get();
        } catch (Exception e){
            log.error("根据ID【{}】获取数据错误：{}", id, e);
            throw new SymServiceException(ResultEnum.QUERY_BYID_ERROR);
        }
        return result;
    }

    @Override
    public List<T> findAll() throws SymServiceException {
        List<T> resultList;
        try {
            resultList = Lists.newArrayList(repository.findAll());
        }catch (Exception e){
            log.error("获取全部信息错误：{}", e);
            throw new SymServiceException(ResultEnum.SAVE_DATA_ERROR);
        }
        return resultList;
    }
}
